<template>
	<view class="menu-container">
		<view class="menu-header" :animation="headerAnim" v-show="store.isMenu">
			<text class="iconfont icon-arrdown fanhui"></text>
			<text class="iconfont icon-gengduo1 genduo"></text>
		</view>
		<view class="menu-backend" :animation="backendAnim" v-show="store.isMenu">
			<view class="menu-top-box">
				<view class="menu-btn" @click="previousChapter">
					上一章
				</view>
				<view class="novel-slider-container">
					<slider :min="0" :max="100" :step="1" :value="Number(textLayoutStore.readingProgress)"
						@change="onSliderChange" show-value activeColor="#ff0307" backgroundColor="#bababa" />
				</view>
				<view class="menu-btn" @click="nextChapter" style="margin-left: -30px;">
					下一章
				</view>
			</view>

			<view class="menu-bottom-box">
				<view class="menu-option" @click="showCatalogue">
					<text class="iconfont icon-langdu-liebiao mulv"></text>
					<view class="menu-text">
						目录·想法
					</view>
				</view>
				<view class="menu-option" @click="showBrightness">
					<text class="iconfont icon-liangdu2 liangdu"></text>
					<view class="menu-text">
						护眼·亮度
					</view>
				</view>
				<view class="menu-option" @click="showVoiceread">
					<text class="iconfont icon-zujian-icon-langdu langdu"></text>
					<view class="menu-text">
						语音朗读
					</view>
				</view>
				<view class="menu-option" @click="showReadsetting">
					<text class="iconfont icon-shezhi yuedu"></text>
					<view class="menu-text">
						阅读设置
					</view>
				</view>

				<view class="light-mode">
					<text class="iconfont icon-a-15Aliangdu" v-show="isLightMode" @click="changebright"></text>
					<text class="iconfont icon-a-15Bliangdu-" v-show="!isLightMode" @click="changedark"></text>
				</view>
			</view>
		</view>

	</view>
</template>

<script setup>
	import '@/common/iconfont.css';
	import {
		ref,
		onMounted,
		onUnmounted,
		watch
	} from 'vue';
	import {
		useNovelStore
	} from '../../common/novel/novel.js';
	import {
		useTextLayoutStore
	} from '../../common/novel/textLayout.js';
	import {
		useComStore
	} from '../../common/common.js';
	import {
		useVoiceReadStore
	} from '../../common/love/leason.js';
	
	// 导入离线TTS插件
	let TTSSpeech;
	try {
		// 尝试加载MT-TTS-Speech模块
		TTSSpeech = uni.requireNativePlugin("MT-TTS-Speech");
		console.log('成功加载MT-TTS-Speech模块');
	} catch (error) {
		console.error('加载MT-TTS-Speech模块失败:', error);
		TTSSpeech = null;
	}
	
	// 检查TTS插件是否可用
	const isTTSAvailable = ref(!!TTSSpeech);
	
	// 检查插件是否正确加载
	const checkTTSPlugin = () => {
		if (!TTSSpeech) {
			try {
				// 尝试重新加载插件
				TTSSpeech = uni.requireNativePlugin("MT-TTS-Speech");
				if (TTSSpeech) {
					isTTSAvailable.value = true;
					console.log('MT-TTS-Speech模块加载成功');
					return true;
				}
			} catch (error) {
				console.error('MT-TTS-Speech模块不可用，请检查manifest.json配置和自定义基座:', error);
			}
			
			uni.showModal({
				title: '提示',
				content: '当前运行的基座不包含原生插件[MT-TTS-Speech]，请在manifest中配置该插件，重新制作包括该原生插件的自定义运行基座',
				showCancel: false
			});
			
			isTTSAvailable.value = false;
			return false;
		}
		return true;
	};

	// 初始化 store
	const store = useNovelStore();
	const textLayoutStore = useTextLayoutStore();
	const comStore = useComStore();
	const voiceReadStore = useVoiceReadStore();

	// 本地状态（非全局共享）
	const isLightMode = ref(false);
	const headerAnim = ref(null);
	const backendAnim = ref(null);
	
	// TTS状态
	const isReady = ref(false);

	const changebright = () => {
		isLightMode.value = false
		comStore.setPageColor('#ffe3a0');
		comStore.setFontColor('#000');
	};
	const changedark = () => {
		isLightMode.value = true
		comStore.setPageColor('#4a4e51');
		comStore.setFontColor('#dcf9ff');
	};
	// 章节导航
	const previousChapter = () => {
		if (textLayoutStore.currentChapter > 0) {
			textLayoutStore.jumpToChapter(textLayoutStore.currentChapter - 1);
		}
	};

	const nextChapter = () => {
		if (textLayoutStore.currentChapter < textLayoutStore.chapters.length - 1) {
			textLayoutStore.jumpToChapter(textLayoutStore.currentChapter + 1);
		}
	};

	// 进度条变化处理
	const onSliderChange = (e) => {
		const targetPage = Math.round((e.detail.value / 100) * (textLayoutStore.totalPages - 1)) + 1;
		textLayoutStore.currentPage = targetPage;
		textLayoutStore.updateCurrentChapter();
	};

	// 初始化TTS引擎
	const initTTS = () => {
		console.log('>> TTS:init...')
		
		// 检查插件是否可用
		if (!checkTTSPlugin()) {
			console.error('TTS插件不可用，可能未在manifest.json中正确配置');
			// 回退到voiceReadStore的原生实现
			return;
		}
		
		try {
			TTSSpeech.init((callback) => {
				isReady.value = true;
				console.log('>> tts: init success');
				
				// 注册TTS事件回调
				try {
					TTSSpeech.onDone((res) => {
						console.log(">> tts: play end " + res);
						
						// 如果启用了自动翻页，继续朗读下一页
						if (voiceReadStore.autoNextPage) {
							uni.$emit('voiceReadNextPage');
						}
					});
				} catch (error) {
					console.error('注册TTS事件回调失败:', error);
				}
			});
		} catch (error) {
			console.error('TTS初始化失败:', error);
			// 回退到voiceReadStore的原生实现
		}
	};
	
	// 播放TTS
	const playTTS = (text) => {
		// 检查插件是否可用
		if (!checkTTSPlugin()) {
			console.error('TTS插件不可用，语音朗读功能无法使用');
			uni.showToast({
				title: '离线语音朗读不可用',
				icon: 'none'
			});
			return;
		}
		
		if (!isReady.value) {
			console.log('TTS引擎未初始化，正在初始化...');
			initTTS();
			setTimeout(() => {
				playTTS(text);
			}, 500);
			return;
		}
		
		try {
			console.log('>> tts: play...');
			const res = TTSSpeech.speak({
				text: text
			});
			console.log('>> tts: play result = ' + res);
			
			// 更新voiceReadStore状态，但不使用其在线TTS功能
			voiceReadStore.isReading = true;
			voiceReadStore.isPaused = false;
			voiceReadStore.readingText = text;
			
			// 开始计时
			voiceReadStore.startTimer();
		} catch (error) {
			console.error('TTS播放失败:', error);
			uni.showToast({
				title: '离线语音朗读失败',
				icon: 'none'
			});
		}
	};

	// 初始化动画
	onMounted(() => {
		// 创建动画实例
		headerAnim.value = uni.createAnimation({
			duration: 300,
			timingFunction: 'ease-in-out',
			delay: 0
		});

		backendAnim.value = uni.createAnimation({
			duration: 300,
			timingFunction: 'ease-in-out',
			delay: 0
		});

		// 初始隐藏动画
		headerAnim.value.translateY(-100).step();
		backendAnim.value.translateY(200).step();

		// 导出动画配置
		headerAnim.value = headerAnim.value.export();
		backendAnim.value = backendAnim.value.export();

		// 延迟执行入场动画
		setTimeout(() => {
			showMenus();
		}, 50);
		
		// 初始化TTS引擎
		initTTS();
		
		// 监听点击事件，处理语音朗读的暂停和继续
		uni.$on('novelPageClick', handleNovelClick);
		
		// 监听语音朗读组件状态变化 - 只在退出语音朗读时停止朗读，不在关闭界面时停止
		watch(() => store.isVoiceread, (newVal, oldVal) => {
			console.log('isVoiceread变化:', oldVal, '->', newVal);
			// 如果有专门标记需要停止朗读，才停止
			if (!newVal && voiceReadStore.isReading && voiceReadStore.shouldStopOnClose) {
				console.log('检测到需要停止朗读的标记，停止朗读');
				stopTTS();
				// 重置标记
				voiceReadStore.shouldStopOnClose = false;
			}
		});
		
		// 监听语音朗读组件发出的事件
		uni.$on('voiceReadReady', handleVoiceReadReady);
		uni.$on('voiceRateChange', handleVoiceRateChange);
		uni.$on('voiceTypeChange', handleVoiceTypeChange);
		uni.$on('exitVoiceRead', handleExitVoiceRead);
		uni.$on('voiceReadNextPage', handleVoiceReadNextPage);
		
		// 监听重新开始朗读事件
		uni.$on('restartTTS', handleRestartTTS);
	});
	
	onUnmounted(() => {
		// 清除事件监听
		uni.$off('novelPageClick', handleNovelClick);
		uni.$off('voiceReadReady', handleVoiceReadReady);
		uni.$off('voiceRateChange', handleVoiceRateChange);
		uni.$off('voiceTypeChange', handleVoiceTypeChange);
		uni.$off('exitVoiceRead', handleExitVoiceRead);
		uni.$off('voiceReadNextPage', handleVoiceReadNextPage);
		uni.$off('restartTTS', handleRestartTTS);
		
		// 停止语音朗读
		if (voiceReadStore.isReading) {
			stopTTS();
		}
		
		// 销毁TTS引擎
		if (isTTSAvailable.value) {
			try {
				TTSSpeech.destroy();
			} catch (error) {
				console.error('销毁TTS引擎失败:', error);
			}
		}
	});

	// 显示菜单动画
	const showMenus = () => {
		headerAnim.value = uni.createAnimation({
			duration: 300,
			timingFunction: 'ease-in-out',
			delay: 0
		}).translateY(0).step().export();

		backendAnim.value = uni.createAnimation({
			duration: 300,
			timingFunction: 'ease-in-out',
			delay: 0
		}).translateY(0).step().export();
	};

	// 隐藏菜单动画
	const hideMenus = () => {
		headerAnim.value = uni.createAnimation({
			duration: 300,
			timingFunction: 'ease-in-out',
			delay: 0
		}).translateY(-100).step().export();

		backendAnim.value = uni.createAnimation({
			duration: 300,
			timingFunction: 'ease-in-out',
			delay: 0
		}).translateY(300).step().export();
	};
	// 确保方法暴露给父组件
	defineExpose({
		showMenus,
		hideMenus
	});

	// 显示目录组件（使用全局状态）
	const showCatalogue = () => {
		store.changeisMenu();
		store.isCatalogue = true;
	};

	const showBrightness = () => {
		store.changeisMenu();
		store.isBrightness = true;
	};

	// 语音朗读功能
	const showVoiceread = () => {
		// 关闭菜单
		store.changeisMenu();
		
		// 检查插件是否可用
		if (!checkTTSPlugin()) {
			uni.showModal({
				title: '提示',
				content: '离线语音朗读功能不可用，请在HBuilderX中重新制作包含MT-TTS插件的自定义基座',
				showCancel: false
			});
			return;
		}
		
		// 开始语音朗读当前页面内容
		const currentContent = textLayoutStore.getCurrentPageContent();
		
		// 使用离线TTS播放
		playTTS(currentContent);
		
		// 注意：这里不显示语音朗读界面，只是开始朗读
		// 界面会在点击中间区域时通过handleNovelClick函数显示
	};
	
	// 处理小说页面点击
	const handleNovelClick = (event) => {
		// 检查是否在语音朗读模式
		if (voiceReadStore.isReading) {
			// 获取点击位置是否在中间区域
			const clientX = event.touches[0].clientX;
			const clientY = event.touches[0].clientY;
			const screenWidth = textLayoutStore.screenWidth;
			const screenHeight = textLayoutStore.screenHeight;
			
			// 定义中间区域（屏幕中间30%的区域）
			const middleAreaLeft = screenWidth * 0.35;
			const middleAreaRight = screenWidth * 0.65;
			const middleAreaTop = screenHeight * 0.35;
			const middleAreaBottom = screenHeight * 0.65;
			
			// 检查点击是否在中间区域
			const isMiddleArea = (
				clientX >= middleAreaLeft && 
				clientX <= middleAreaRight && 
				clientY >= middleAreaTop && 
				clientY <= middleAreaBottom
			);
			
			console.log('点击坐标:', clientX, clientY);
			console.log('中间区域:', middleAreaLeft, middleAreaRight, middleAreaTop, middleAreaBottom);
			console.log('是否在中间区域:', isMiddleArea);
			console.log('当前isVoiceread状态:', store.isVoiceread);
			
			if (isMiddleArea) {
				if(store.isVoiceread==false){
					// 点击中间区域，显示语音朗读组件
					console.log('点击中间区域，显示语音朗读组件');
					pauseTTS();
					
					// 直接设置状态，不使用changeisVoiceread()方法
					store.isVoiceread = true;
					// store.changeisVoiceread();
					console.log('设置后isVoiceread:', store.isVoiceread);
					
					// 确保其他组件状态为false
					store.isCatalogue = false;
					store.isBrightness = false;
					store.isReadsetting = false;
					store.isTiming = false;
					store.isPageway = false;
					
					// 阻止翻页
					if (typeof event.stopPropagation === 'function') {
						event.stopPropagation();
					}
					return false;
				}
				else{
					// 如果已经显示语音朗读组件
					// 点击在其他区域，关闭组件并继续朗读
					console.log('已显示语音朗读组件，点击在组件外部');
					
					// 先继续朗读
					resumeTTS();
					// 确保不会在关闭界面时停止朗读
					voiceReadStore.shouldStopOnClose = false;
					
					// 关闭界面
					store.isVoiceread = false;
					console.log('设置后isVoiceread:', store.isVoiceread);
				}
				
			} else {
				// 点击在其他区域，暂停/继续朗读
				console.log('点击其他区域，切换暂停/继续状态');
				if (voiceReadStore.isPaused) {
					resumeTTS();
				} else {
					pauseTTS();
				}
			}
			
			// 阻止翻页
			if (typeof event.stopPropagation === 'function') {
				event.stopPropagation();
			}
			return false;
		}
		
		// 非朗读模式，不干预正常点击行为
		return true;
	};

	const showReadsetting = () => {
		store.changeisMenu();
		store.isReadsetting = true;
	};

	// 处理语音朗读组件准备就绪
	const handleVoiceReadReady = (data) => {
		// 更新语音朗读选项
		updateTTSSettings(data);
	};
	
	// 处理语速变化
	const handleVoiceRateChange = (rate) => {
		// 更新语音朗读选项
		updateTTSSettings({ rate });
	};
	
	// 处理声音类型变化
	const handleVoiceTypeChange = (voiceType) => {
		// 更新语音朗读选项
		updateTTSSettings({ voiceType });
	};
	
	// 更新TTS设置
	const updateTTSSettings = (settings) => {
		// 更新voiceReadStore状态
		voiceReadStore.updateVoiceSettings(settings);
		
		// 检查插件是否可用
		if (!checkTTSPlugin()) {
			console.log('TTS插件不可用，无法更新TTS设置');
			return;
		}
		
		try {
			// 设置TTS语速
			if (settings.rate !== undefined) {
				// 将rate(0.5-2.0)转换为TTS需要的语速(0-100)
				const ttsSpeed = Math.round((settings.rate - 0.5) * 100 / 1.5);
				TTSSpeech.setSpeed(ttsSpeed);
			}
			
			// 根据声音类型设置音调
			if (settings.voiceType) {
				let ttsPitch = 50; // 默认音调
				
				switch (settings.voiceType) {
					case 'female':
						ttsPitch = 60; // 女声音调高一些
						break;
					case 'male':
						ttsPitch = 40; // 男声音调低一些
						break;
					case 'youngMale':
						ttsPitch = 50; // 青年男声
						break;
					case 'femaleHost':
						ttsPitch = 65; // 女主播
						break;
					case 'child':
						ttsPitch = 75; // 儿童声音
						break;
				}
				
				TTSSpeech.setPitch(ttsPitch);
			}
		} catch (error) {
			console.error('更新TTS设置失败:', error);
		}
	};
	
	// 暂停TTS播放
	const pauseTTS = () => {
		if (!voiceReadStore.isReading || voiceReadStore.isPaused) return;
		
		// 检查插件是否可用
		if (!checkTTSPlugin()) {
			console.error('TTS插件不可用，无法暂停朗读');
			return;
		}
		
		try {
			TTSSpeech.stop();
			voiceReadStore.isPaused = true;
			console.log('暂停朗读');
		} catch (error) {
			console.error('暂停朗读失败:', error);
			uni.showToast({
				title: '暂停朗读失败',
				icon: 'none'
			});
		}
	};
	
	// 继续TTS播放
	const resumeTTS = () => {
		if (!voiceReadStore.isReading || !voiceReadStore.isPaused) return;
		
		// 检查插件是否可用
		if (!checkTTSPlugin()) {
			console.error('TTS插件不可用，无法继续朗读');
			return;
		}
		
		try {
			// 由于TTS没有暂停功能，只能重新播放
			playTTS(voiceReadStore.readingText);
			voiceReadStore.isPaused = false;
			console.log('继续朗读');
		} catch (error) {
			console.error('继续朗读失败:', error);
			uni.showToast({
				title: '继续朗读失败',
				icon: 'none'
			});
		}
	};
	
	// 停止TTS播放
	const stopTTS = () => {
		if (!voiceReadStore.isReading) return;
		
		// 检查插件是否可用
		if (!checkTTSPlugin()) {
			console.error('TTS插件不可用，无法停止朗读');
			voiceReadStore.isReading = false;
			voiceReadStore.isPaused = false;
			voiceReadStore.stopTimer();
			return;
		}
		
		try {
			TTSSpeech.stop();
			
			voiceReadStore.isReading = false;
			voiceReadStore.isPaused = false;
			voiceReadStore.currentPosition = 0;
			console.log('停止朗读');
			
			// 停止计时
			voiceReadStore.stopTimer();
			
		} catch (error) {
			console.error('停止朗读失败:', error);
			voiceReadStore.isReading = false;
			voiceReadStore.isPaused = false;
			voiceReadStore.stopTimer();
		}
	};
	
	// 处理退出语音朗读
	const handleExitVoiceRead = () => {
		console.log('收到退出语音朗读事件');
		// 设置shouldStopOnClose标记，确保关闭界面时会停止朗读
		voiceReadStore.shouldStopOnClose = true;
		// 由于voiceread.vue组件已经自己关闭了界面，这里不需要再设置isVoiceread
	};

	// 处理自动翻页朗读
	const handleVoiceReadNextPage = () => {
		// 如果不是在语音朗读组件中，自动翻到下一页并继续朗读
		if (!store.isVoiceread && voiceReadStore.autoNextPage) {
			setTimeout(() => {
				textLayoutStore.nextPage();
				// 继续朗读下一页
				setTimeout(() => {
					const currentContent = textLayoutStore.getCurrentPageContent();
					playTTS(currentContent);
				}, 500);
			}, 100);
		}
	};

	// 处理重新开始朗读事件
	const handleRestartTTS = () => {
		if (voiceReadStore.isReading) {
			// 重新开始朗读当前文本
			playTTS(voiceReadStore.readingText);
			console.log('重新开始朗读，应用新的语音设置');
		}
	};
</script>

<style lang="scss">
	@import '/common/novel/novel.scss';

	.menu-header {
		position: fixed;
		top: 0px;
		width: 100vw;
		height: 10vh;
		background-color: var(--bg-color);
		display: flex;
		justify-content: space-between;
		align-items: center;
		z-index: 999;
	}

	.menu-backend {
		position: fixed;
		bottom: 0;
		width: 100vw;
		height: 200px;
		background-color: var(--bg-color);
		z-index: 999;

		.menu-top-box {
			width: 100%;
			height: 50px;
			margin-top: 10px;
			display: flex;
			align-items: center;
			justify-content: center;

			.menu-btn {
				width: 100px;
				height: 50px;
				display: flex;
				align-items: center;
				justify-content: center;
				color: var(--font-color);
			}

			.novel-slider-container {
				margin-left: -10px;
				height: 36px;
				width: calc(100vw - 50px);
				// background-color: #fff;
			}
		}

		.menu-bottom-box {
			width: 100%;
			margin-top: 5%;
			height: 50%;
			display: flex;

			.menu-option {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: flex-start;


				text {
					font-size: 24px;
					color: var(--font-color);
					margin: auto;
					margin-bottom: -20px;
				}

				.menu-text {
					font-size: 18px;
					color: var(--font-color);
					margin: auto;
				}
			}

			.light-mode {
				position: absolute;
				bottom: 220px;
				left: 15px;
				width: 50px;
				height: 50px;
				border-radius: 50%;
				background-color: var(--bg-color);
				display: flex;
				justify-content: center;
				align-items: center;

				text {
					font-size: 40px;
					color: var(--font-color);
				}
			}
		}
	}

	.fanhui {
		font-size: 30px;
		margin-left: 10px;
	}

	.genduo {
		font-size: 20px;
		margin-right: 10px;
	}

	.light-content {
		width: 50px;
		height: 10vh;
		background-color: var(--bg-color);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.mulv {
		font-size: 24px;
	}

	.liangdu {
		font-size: 24px;
	}

	.langdu {
		font-size: 24px;
	}

	.yuedu {
		font-size: 24px;
	}

	.yejian {
		font-size: 24px;
	}
</style>